package zaplogger

import (
	"github.com/natefinch/lumberjack"
	"go-caipu/pkg/setting"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"math"
	"path/filepath"
	"time"
)

func NewJobLogger(cfg *setting.Cfg) *zap.Logger {
	// 配置日志轮转
	gormLogRotate := &lumberjack.Logger{
		Filename:   filepath.Join(cfg.Application.LogsPath, "go-caipu-job.log"),
		MaxSize:    100,
		MaxBackups: 30,
		MaxAge:     30,
		Compress:   true,
	}
	// 配置编码器
	encoderConfig := zapcore.EncoderConfig{
		TimeKey:       "time",
		LevelKey:      "level",
		NameKey:       "logger",
		CallerKey:     zapcore.OmitKey, // GORM日志不需要调用者信息
		FunctionKey:   zapcore.OmitKey,
		MessageKey:    "msg",
		StacktraceKey: "stacktrace",
		LineEnding:    zapcore.DefaultLineEnding,
		EncodeLevel:   zapcore.LowercaseLevelEncoder,
		EncodeTime: func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
			enc.AppendString(t.Format("2006-09-13 15:04:05.281")) // 只保留 "时:分:秒"
		},
		EncodeDuration: func(d time.Duration, enc zapcore.PrimitiveArrayEncoder) {
			// 将持续时间转换为毫秒，并保留 2 位小数
			ms := float64(d.Nanoseconds()) / float64(time.Millisecond)
			enc.AppendFloat64(math.Round(ms*100) / 100) // 四舍五入保留 2 位小数
		},
	}
	// 创建核心
	jobCore := zapcore.NewCore(
		zapcore.NewJSONEncoder(encoderConfig),
		zapcore.AddSync(gormLogRotate),
		zap.InfoLevel,
	)
	// 创建zap logger
	return zap.New(jobCore)

}
